// 使用环境变量
require('dotenv').config(); // 加载.env文件中的环境变量
const port = process.env.PORT || 8000; // 如果环境变量不存在，使用默认值3000

const express = require('express');
const bodyParser = require('body-parser');
const multer = require('multer')
const cors = require('cors');
const path = require('path');
const { db } = require('./db/DbConnect');

const app = express()
const multerUpload = require('./utils/multerUpload');
const routers = require('./routers');
const { log } = require('console');

app.use(cors()); // 跨域请求
app.use(multerUpload.any()) // 允许该端口下任何路径上传
app.use(bodyParser.json()) // 解析json数据
app.use(bodyParser.urlencoded({ extended: true })) // 解析urlencoded数据


const ADMIN_TOKEN_PATH = '/_token'
app.all("*", async (req, res, next) => {
    if (req.path.indexOf(ADMIN_TOKEN_PATH) > -1) {
        try {
            let { token } = req.headers;
            let admin_token_sql = `SELECT * FROM admin WHERE token =?`
            let adminResult = await db.async.all(admin_token_sql, [token])
            log(adminResult)
            if (!adminResult.length) {
                throw new Error()
            } else {
                next()
            }
        } catch (error) {
            res.status(500).send({
                code: 500,
                msg: "请先登录",
            })
        }
    } else {
        next()
    }
})

app.use('/', express.static(path.join(__dirname, '/public')))
app.use('/uploads', express.static(path.join(__dirname, '/uploads')))

app.use('/api', routers) // api

app.listen(port, () => {
    console.log(`Server running at http://localhost:${port}`);
})